package com.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.mapper.MediaProcessMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.model.po.RestResponse;
import com.xuecheng.media.service.MediaFileService;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Mr.M
 * @version 1.0
 * @description TODO
 * @date 2022/9/10 8:58
 */
@Service
@Slf4j
public class MediaFileServiceImpl implements MediaFileService {

    @Autowired
    MediaFilesMapper mediaFilesMapper;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MediaFileService currentProxy;
    @Autowired
    private MediaProcessMapper mediaProcessMapper;

    //普通文件桶
    @Value("${minio.bucket.files}")
    private String bucket_mediafiles;

    @Value("${minio.bucket.videofiles}")
    private String bucket_video;

    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

    /**
     * 根据扩展名获取mimeType
     *
     * @param extension
     * @return
     */
    private String getMimeType(String extension) {
        if (extension == null)
            extension = "";
        //根据扩展名取出mimeType
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        //通用mimeType，字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if (extensionMatch != null) {
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }

    /**
     * @param localFilePath 文件地址
     * @param bucket        桶
     * @param objectName    对象名称
     * @return void
     * @description 将文件写入minIO
     * @author Mr.M
     * @date 2022/10/12 21:22
     */
    public boolean addMediaFilesToMinIO(String localFilePath, String mimeType, String bucket, String objectName) {
        try {
            UploadObjectArgs testbucket = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(objectName)
                    .filename(localFilePath)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(testbucket);
            log.debug("上传文件到minio成功,bucket:{},objectName:{}", bucket, objectName);
            System.out.println("上传成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件到minio出错,bucket:{},objectName:{},错误原因:{}", bucket, objectName, e.getMessage(), e);
            XueChengPlusException.cast("上传文件到文件系统失败");
        }
        return false;
    }

    /**
     * 存储到minio中目录格式为年月日
     *
     * @return
     */
    private String getDefaultFolderPath() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(new Date()).replace("-", "/") + "/";
    }


    /**
     * 获取文件的md5
     *
     * @param file
     * @return
     */
    private String getFileMd5(File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String fileMd5 = DigestUtils.md5Hex(fileInputStream);
            return fileMd5;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param companyId           机构id
     * @param fileMd5             文件md5值
     * @param uploadFileParamsDto 上传文件的信息
     * @param bucket_mediafiles   桶
     * @param objectName          对象名称
     * @return com.xuecheng.media.model.po.MediaFiles
     * @description 将文件信息添加到文件表
     * @author Mr.M
     * @date 2022/10/12 21:22
     */
    @Transactional
    public MediaFiles addMeaiaFilesToDb(Long companyId, String fileMd5, UploadFileParamsDto uploadFileParamsDto, String objectName, String bucket_mediafiles) {
        //先查询数据
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (mediaFiles == null) {
            mediaFiles = new MediaFiles();
            //拷贝基本信息
            BeanUtils.copyProperties(uploadFileParamsDto, mediaFiles);
            mediaFiles.setId(fileMd5);
            mediaFiles.setFileId(fileMd5);
            mediaFiles.setCompanyId(companyId);
            //获取源文件名的contentType
            String filename = uploadFileParamsDto.getFilename();
            String mimeType = getMimeType(filename.substring(filename.lastIndexOf(".")));
            if (mimeType.contains("image") || mimeType.contains("mp4")) {
                mediaFiles.setUrl("/" + bucket_mediafiles + "/" + objectName);
            }
            mediaFiles.setBucket(bucket_mediafiles);
            mediaFiles.setFilePath(objectName);
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setAuditStatus("002003");
            mediaFiles.setStatus("1");
            //保存文件信息到文件表
            int insert = mediaFilesMapper.insert(mediaFiles);
            if (insert < 0) {
                log.error("保存文件信息到数据库失败,{}", mediaFiles.toString());
                XueChengPlusException.cast("保存文件信息失败");
                return null;
            }
            log.debug("保存文件信息到数据库成功,{}", mediaFiles.toString());
            //记录待处理任务
            addWaitingTask(mediaFiles);
            log.debug("保存文件信息到数据库成功,{}", mediaFiles.toString());
            return mediaFiles;

        }
        return mediaFiles;
    }

    /**
     * 添加待处理任务
     *
     * @param mediaFiles
     */
    private void addWaitingTask(MediaFiles mediaFiles) {
        //获取到文件的minetype
        String filename = mediaFiles.getFilename();
        //文件扩展名
        String minetype = filename.substring(filename.lastIndexOf("."));
        String mimeType = getMimeType(minetype);

        //通过minmetype判断如果是avi则写入待处理任务表中
        if (mimeType.equals("video/x-msvideo")) {
            MediaProcess mediaProcess = new MediaProcess();
            BeanUtils.copyProperties(mediaFiles, mediaProcess);
            mediaProcess.setCreateDate(LocalDateTime.now());
            mediaProcess.setStatus("1");//未处理
            mediaProcess.setFailCount(0);//失败默认0次
            mediaProcess.setUrl(null);
            mediaProcessMapper.insert(mediaProcess);

        }

    }

    /**
     * 检查文件
     *
     * @param fileMd5
     * @return
     */
    @Override
    public RestResponse<Boolean> checkFile(String fileMd5) {
        //查询文件信息
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (mediaFiles != null) {

            try {
                InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                        .bucket(mediaFiles.getBucket())
                        .object(mediaFiles.getFilePath())
                        .build());
                if (inputStream != null) {
                    RestResponse.success(true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        //文件不存在
        return RestResponse.success(false);
    }

    /**
     * 检查分块
     *
     * @param fileMd5
     * @param chunk
     * @return
     */

    @Override
    public RestResponse<Boolean> checkchunk(String fileMd5, int chunk) {
        //得到分块目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        //得到分块文件的路径
        String chunkFilePath = chunkFileFolderPath + chunk;

        try {
            InputStream inputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucket_video)
                            .object(chunkFilePath)
                            .build()
            );
            if (inputStream != null) {
                //分块也存在
                return RestResponse.success(true);
            }
        } catch (Exception e) {
        }
        return RestResponse.success(false);
    }

    /**
     * 上传分块文件
     *
     * @param absolutePath
     * @param chunk
     * @param fileMd5
     * @return
     */
    @Override
    public RestResponse uploadChunk(String absolutePath, int chunk, String fileMd5) {

        //获取分块文件的目录
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        //得到分块文件的路径
        String chunkFilePath = chunkFileFolderPath + chunk;
        String mimeType = getMimeType(null);
        //存储到minio中
        boolean b = addMediaFilesToMinIO(absolutePath, mimeType, bucket_video, chunkFilePath);
        if (!b) {
            log.debug("上传分块文件失败:{}", chunkFilePath);
            return RestResponse.validfail(false, "上传分块失败");
        } else {
            log.debug("上传分块文件成功:{}", chunkFilePath);
            return RestResponse.success(true);
        }
    }

    //得到分块文件的目录
    private String getChunkFileFolderPath(String fileMd5) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + "chunk" + "/";
    }

    /**
     * 上传图片
     *
     * @param companyId           机构id
     * @param uploadFileParamsDto 上传文件信息
     * @param localFilePath       文件磁盘路径
     * @param objectName
     * @return
     */
//    @Transactional
    @Override
    public UploadFileResultDto uploadFile(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath, String objectName) {



        File file = new File(localFilePath);
        if (!file.exists()) {
            XueChengPlusException.cast("文件不存在");
        }
        //1.上传文件到minio
        //文件名
        String filename = uploadFileParamsDto.getFilename();
        //拿到扩展名
        String extension = filename.substring(filename.lastIndexOf("."));
        //拿到mimeType
        String mimeType = getMimeType(extension);
        //存储到minio中目录格式为年月日---子目录
        String defaultFolderPath = getDefaultFolderPath();
        //拿到文件的md5值
        String fileMd5 = getFileMd5(file);
        //存储到minio中的对象名(带目录)
        if(StringUtils.isEmpty(objectName)){
            //将子目录，MD5值和扩展名拼接起来
            objectName =  defaultFolderPath + fileMd5 + extension;
        }
//            objectName = defaultFolderPath + fileMd5 + extension;
        //上传文件
        boolean b = addMediaFilesToMinIO(localFilePath, mimeType, bucket_mediafiles, objectName);
        //2.把图片信息保存到数据库
        MediaFiles mediaFiles = currentProxy.addMeaiaFilesToDb(companyId, fileMd5, uploadFileParamsDto, objectName, bucket_mediafiles);
        if (mediaFiles == null) {
            XueChengPlusException.cast("文件上传后保存信息失败");
        }
        UploadFileResultDto uploadFileResultDto = new UploadFileResultDto();
        BeanUtils.copyProperties(mediaFiles, uploadFileResultDto);
        mediaFiles.setFileSize(file.length());
        //返回数据
        return uploadFileResultDto;
    }

    /**
     * 合并分块
     *
     * @param companyId
     * @param fileMd5
     * @param chunkTotal
     * @param uploadFileParamsDto
     * @return
     */
    @Override
    public RestResponse mergechunks(Long companyId, String fileMd5, int chunkTotal, UploadFileParamsDto uploadFileParamsDto) {
        //获取分块文件路径
        String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
        //组成分块文件路径
        List<ComposeSource> sourceList = Stream.iterate(0, i -> ++i).limit(chunkTotal).map(i -> ComposeSource.builder()
                .bucket(bucket_video)
                .object(chunkFileFolderPath.concat(Integer.toString(i)))
                .build()).collect(Collectors.toList());


        //========合并分块=========
        //文件名称
        String filename = uploadFileParamsDto.getFilename();
        //文件扩展名
        String exName = filename.substring(filename.lastIndexOf("."));
        //合并文件路径
        String mergeFilePath = getFilePathByMd5(fileMd5, exName);
        try {
            minioClient.composeObject(ComposeObjectArgs
                    .builder()
                    .bucket(bucket_video)
                    .sources(sourceList)
                    .object(mergeFilePath)
                    .build());
            log.debug("合并文件成功:{}", mergeFilePath);
        } catch (Exception e) {
            log.debug("合并文件失败,fileMd5:{},异常:{}", fileMd5, e.getMessage(), e);
            return RestResponse.validfail(false, "合并文件失败。");
        }


        // ====验证md5====
        //下载合并后的文件
        File minioFile = downloadFileFromMinIO(bucket_video, mergeFilePath);
        if (minioFile == null) {
            log.debug("下载合并后文件失败,mergeFilePath:{}", mergeFilePath);
            return RestResponse.validfail(false, "下载合并后文件失败。");
        }

        try (InputStream inputStream = new FileInputStream(minioFile);) {
            //文件上传后的md5值
            String md5Hex = DigestUtils.md5Hex(inputStream);
            //比较md5值，不一致则说明文件不完整
            if (!md5Hex.equals(fileMd5)) {
                return RestResponse.validfail(false, "文件合并校验失败，最终上传失败。");
            }
            //文件大小
            uploadFileParamsDto.setFileSize(minioFile.length());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (minioFile != null) {
                minioFile.delete();
            }
        }

        //====文件入库======
        currentProxy.addMeaiaFilesToDb(companyId, fileMd5, uploadFileParamsDto, mergeFilePath, bucket_video);


        //=====清除分块文件=====
        clearChunkFiles(chunkFileFolderPath, chunkTotal);


        return RestResponse.success(true);
    }

    /**
     * 清除分块文件
     *
     * @param chunkFileFolderPath 分块文件路径
     * @param chunkTotal          分块总数
     */
    private void clearChunkFiles(String chunkFileFolderPath, int chunkTotal) {

        //创建DeleteObject对象
        List<DeleteObject> objectList = Stream.iterate(0, i -> ++i)
                .limit(chunkTotal)
                .map(i -> new DeleteObject(chunkFileFolderPath.concat(Integer.toString(i))))
                .collect(Collectors.toList());

        //进行删除分块文件
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs
                .builder()
                .bucket(bucket_video)
                .objects(objectList)
                .build());
        //上面方法并没有真正的清楚，需要遍历清楚
        results.forEach(f -> {
            DeleteError deleteError = null;
            try {
                deleteError = f.get();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("清楚分块文件失败,objectname:{}", deleteError.objectName(), e);
            }
        });


    }


    /**
     * 下载minio文件
     *
     * @param bucketVideo
     * @param mergeFilePath
     * @return
     */
    public File downloadFileFromMinIO(String bucketVideo, String mergeFilePath) {
        //创建临时文件
        File minioFile = null;
        FileOutputStream fileOutputStream = null;
        try {
            InputStream inputStream = minioClient.getObject(GetObjectArgs
                    .builder()
                    .bucket(bucketVideo)
                    .object(mergeFilePath)
                    .build());
            //创建临时文件
            minioFile = File.createTempFile("minio", "temp");
            fileOutputStream = new FileOutputStream(minioFile);
            IOUtils.copy(inputStream, fileOutputStream);
            return minioFile;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 合并文件路径，成为文件
     *
     * @param fileMd5
     * @param exName
     * @return
     */
    private String getFilePathByMd5(String fileMd5, String exName) {

        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + fileMd5 + exName;
    }

    @Override
    public MediaFiles getFileById(String mediaId) {
        MediaFiles mediaFiles = mediaFilesMapper.selectById(mediaId);
        if (mediaFiles == null || StringUtils.isEmpty(mediaFiles.getUrl())) {
            XueChengPlusException.cast("视频还没有转码");
        }
        return mediaFiles;
    }
}
